import random
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from image_handle import get_image,get_diffrent_loaction

DIRVER_PATH = 'driver/chromedriver.exe'
class HuXiuLogin:
    def __init__(self):
        self.__creatdriver__()

    def __creatdriver__(self):
        driver = webdriver.Chrome(executable_path=DIRVER_PATH)
        self.drvier = driver
        driver.set_page_load_timeout(10)
        driver.set_script_timeout(10)
        driver.set_window_size(1920,1080)

    def __quitdriver__(self):
        if self.drvier:
            self.drvier.quit()

    def visit_huxiu(self):
        url = 'https://www.huxiu.com/'
        self.drvier.get(url)
        register = self.drvier.find_element_by_xpath("//a[@class='js-register']")
        register.click()
        time.sleep(5)

        #完整图片的xpaths
        complete_image_xpaths = "//div[@class='gt_cut_fullbg gt_show']/div"
        #有缺口的图片xpaths
        break_image_xpaths = "//div[@class='gt_cut_bg gt_show']/div"
        complete_image = get_image(self.drvier,complete_image_xpaths)
        break_image = get_image(self.drvier,break_image_xpaths)

        #获得缺口x坐标
        loc_x = get_diffrent_loaction(complete_image,break_image)
        self.move(loc_x)

    def move(self,length):
        '''

        :param length:移动距离
        :return:
        '''

        track_list = self.track(length)

        #找到滑动模块
        slider = self.drvier.find_element_by_xpath("//div[@class='gt_slider_knob gt_show']")
        location = slider.location
        y = location['y']

        ActionChains(self.drvier).click_and_hold(slider).perform()
        time.sleep(0.5)

        for track in track_list:
            y_offset = random.randint(100, 110)
            ActionChains(self.drvier).move_to_element_with_offset(to_element=slider,xoffset=track+22,yoffset=y-y_offset).perform()
            time.sleep(random.randint(10,30)/100)
        #往回移点点
        for _ in range(5):
            y_offset = random.randint(100, 110)
            ActionChains(self.drvier).move_to_element_with_offset(to_element=slider,xoffset=21,yoffset=y - y_offset).perform()
            time.sleep(0.2)

        ActionChains(self.drvier).release(on_element=slider).perform()

        # self.__quitdriver__()




    def track(self,length):
        '''
        生成x移动轨迹
        :param length:
        :return:
        '''
        track_list = []
        x = random.randint(2,3)

        while length - x >= 5:
            track_list.append(x)
            length = length - x
            x = random.randint(2,4)

        for i in range(length):
            track_list.append(1)

        return track_list


if __name__ == '__main__':
    huxiu = HuXiuLogin()
    huxiu.visit_huxiu()




